package com.fhz.a2102shopjava.ui.login.data;

import androidx.lifecycle.LiveData;

import com.fhz.a2102shopjava.callback.ApiResponse;
import com.fhz.a2102shopjava.ui.login.data.model.LoggedInUser;

import javax.inject.Inject;

/**
 * Class that requests authentication and user information from the remote data source and
 * maintains an in-memory cache of login status and user credentials information.
 */
public class LoginRepository {

    LoginDataSource dataSource;

    // If user credentials will be cached in local storage, it is recommended it be encrypted
    // @see https://developer.android.com/training/articles/keystore
    private LoggedInUser user = null;

    @Inject
    // private constructor : singleton access
    public LoginRepository(LoginDataSource dataSource) {
        this.dataSource = dataSource;
    }

//    public static LoginRepository getInstance(LoginDataSource dataSource) {
//        if (instance == null) {
//            instance = new LoginRepository(dataSource);
//        }
//        return instance;
//    }

    public boolean isLoggedIn() {
        return user != null;
    }

    public void logout() {
        user = null;
        dataSource.logout();
    }

    private void setLoggedInUser(LoggedInUser user) {
        this.user = user;
        // If user credentials will be cached in local storage, it is recommended it be encrypted
        // @see https://developer.android.com/training/articles/keystore
    }


    public LiveData<ApiResponse<LoggedInUser>> register(LoggedInUser hUser){
        return dataSource.register(hUser);
    }

    public LiveData<ApiResponse<LoggedInUser>> login(String username, String password) {
        // handle login
        return dataSource.login(username, password);
//        if (result instanceof Result.Success) {
//            setLoggedInUser(((Result.Success<LoggedInUser>) result).getData());
//        }
//        return result;
    }
}